﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.Web.Mvc;

namespace Kooboo.Commerce.AddIn.Validators
{
    public static class ModelClientMetadataBuilderEx
    {
        public static ModelClientMetadataBuilder<TModel> Validate<TModel>(this ModelClientMetadataBuilder<TModel> builder, string element, IProductAttribute attribute)
        {
            var metadata = new FieldValidationMetadata
            {
                FieldName = element,
            };

            foreach (var rule in attribute.ValidationRules)
            {
                var clientRule = new ModelClientValidationRule();
                clientRule.ValidationType = rule.Validator.Name.ToLowerInvariant();
                clientRule.ErrorMessage = rule.ErrorMessage;

                foreach (var i in rule.Parameters)
                {
                    clientRule.ValidationParameters.Add(i.Name, i.Value);
                }

                metadata.ValidationRules.Add(clientRule);
            }

            builder.Validate(element, metadata);

            return builder;
        }
    }
}
